package com.cskaoyan.gateway.controller.order;

import com.cskaoyan.gateway.utils.TokenUtil;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.order.OrderCoreService;
import com.mall.order.OrderEndService;
import com.mall.order.OrderQueryService;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.dto.*;
import com.mall.user.constants.SysRetCodeConstants;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.UUID;

/**
 * @author break_a_leg
 * @description
 * @date 2021年11月01日 15:40
 */
@RestController
@RequestMapping("/shopping")
public class OrderController {

    // 服务调用的超时时间为3s  服务自动重试次数默认2次（debug时设置0）
    // 消费者启动时检查提供者的状态，默认true，此时先启动提供者会报错，false不检查
    @Reference(timeout = 3000, retries = 0, check = false)
    private OrderCoreService orderCoreService;

    @Reference(timeout = 3000, check = false)
    private OrderQueryService orderQueryService;

    @Reference(timeout = 3000, check = false, retries = 0)
    private OrderEndService orderEndService;



    /**
     * 创建订单
     * @param request
     * @param servletRequest
     * @return
     */
    @PostMapping("/order")
    public ResponseData order(@RequestBody CreateOrderRequest request, HttpServletRequest servletRequest) {
        // 获取token令牌并解析获取userId
        Long uid = TokenUtil.getUserId(servletRequest);
        request.setUserId(uid);

        String username = TokenUtil.getUsername(servletRequest);
        request.setBuyerNickName(username);

        // 设置uniqueKey唯一键  不暴露订单id
        request.setUniqueKey(UUID.randomUUID().toString());

        // 调用服务去实现业务逻辑
        CreateOrderResponse response = orderCoreService.createOrder(request);

        // 响应
        if (response.getCode().equals(OrderRetCode.SUCCESS.getCode())) {
            return new ResponseUtil<>().setData(response.getOrderId());
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }

    /**

     * 取消订单
     * @param
     * @return
     */
    @PostMapping("/cancelOrder")
    public ResponseData cancelOrder(@RequestBody CancelOrderRequest request) {  //传入订单id
        //1.Request封装请求参数
//        CancelOrderRequest request = new CancelOrderRequest();
//        request.setOrderId(id.toString());

        //2.远程调用service层处理----pipeline方式
//        CancelOrderResponse response = orderCoreService.cancelOrder(request);

//        //2.远程调用service层处理----非pipeline方式
        CancelOrderResponse response = orderEndService.cancelOrder(request);

        //3.对返回的数据，进一步封装；响应
        if (OrderRetCode.SUCCESS.getCode().equals(response.getCode())) {
            return new ResponseUtil().setData(response.getResult());     //***********此处对比过，没有问题********
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }

//    /**
//     * 非pipeline方式
//     * @param orderId
//     * @return
//     */
//    @PostMapping("cancelOrder")
//    public ResponseData cancelOrder(@RequestBody Map<String, Long> orderId) {
//        CancelOrderRequest cancelOrderRequest = new CancelOrderRequest();
//        cancelOrderRequest.setOrderId(orderId.get("id").toString());
//        CancelOrderResponse cancelOrderResponse = orderEndService.cancelOrder(cancelOrderRequest);
//        if (cancelOrderResponse.getCode().equals(OrderRetCode.SUCCESS.getCode()))
//            return new ResponseUtil<>().setData(cancelOrderResponse);
//        return new ResponseUtil<>().setErrorMsg(Integer.valueOf(cancelOrderResponse.getCode()), cancelOrderResponse.getMsg());
//    }


    /**
     * 获取当前用户的所有订单
     * @param request
     * @param servletRequest
     * @return
     */
    @GetMapping("/order")
    public ResponseData getAllOrdersByUserId(OrderListRequest request, HttpServletRequest servletRequest) {
        // 获取token令牌并解析获取userId
        Long uid = TokenUtil.getUserId(servletRequest);
        request.setUserId(uid);

        // 调用服务去实现业务逻辑
        OrderListResponse response = orderQueryService.queryAllOrders(request);
        if (response.getCode().equals(OrderRetCode.SUCCESS.getCode())) {
            return new ResponseUtil<>().setData(response.getOrderDetailAndTotal());
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }


    /**
     * 获取指定订单id的订单详情
     * @param orderId
     * @return
     */
    @GetMapping("/order/{orderId}")
    public ResponseData getOrderDetailByOrderId(@PathVariable("orderId") String orderId) {

        OrderDetailRequest request = new OrderDetailRequest();

        request.setOrderId(orderId);

        // 调用服务去实现业务逻辑
        OrderDetailResponse response = orderQueryService.queryOrderDetailByOrderId(request);
        if (response.getCode().equals(OrderRetCode.SUCCESS.getCode())) {
            return new ResponseUtil<>().setData(response);
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }

    /**
     *  删除订单
     *
     */
    @DeleteMapping("order/{id}")
    public ResponseData deleteOrder(@PathVariable("id") String deleteOrderId){
        DeleteOrderRequest deleteOrderRequest = new DeleteOrderRequest();
        deleteOrderRequest.setOrderId(deleteOrderId);

        // 根据订单id删除所有的此id关联的所有表
        // tb_order、tb_order_item、tb_order_shipping
        DeleteOrderResponse deleteOrderResponse = orderCoreService.deleteOrder(deleteOrderRequest);
        // 根据code属性值判断是否成功
        if(deleteOrderResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())){
            // 成功
            return  new ResponseUtil<>().setData("成功");
        }
        // 出错
        return new ResponseUtil<>().setErrorMsg(deleteOrderResponse.getMsg());
    }
}
